<template>
<div class="">
  <div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{path: '/home'}"><i class="el-icon-setting"></i> 首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path: '/article'}">文章</el-breadcrumb-item>
      <el-breadcrumb-item>编辑</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <el-tabs>
    <el-tab-pane label="基本资料">
      <div class="form-box">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="标题">
            <el-input v-model="form.a_title"></el-input>
          </el-form-item>
          <el-form-item label="简介">
              <el-input type="textarea" v-model="form.a_summary"></el-input>
          </el-form-item>

          <el-form-item label="点击量">
            <el-input-number v-model="form.a_click" ></el-input-number>
          </el-form-item>
          <el-form-item label="栏目">
            <el-cascader :options="categorys" v-model="categorySelect" @change="categoryChange"  expand-trigger="hover"></el-cascader>
          </el-form-item>
          <el-form-item label="显示">
            <el-switch on-text="ON" off-text="OFF" on-value="1" off-value="0" v-model="form.a_is_open"></el-switch>
          </el-form-item>

          <el-form-item label="内容">
              <my-editor :imgs="imgs" :content.sync="form.a_content">
              </my-editor>
          </el-form-item>
          <el-form-item label="title">
              <el-input type="textarea" v-model="form.a_web_title"></el-input>
          </el-form-item>
          <el-form-item label="keyword">
              <el-input type="textarea" v-model="form.a_web_keyword"></el-input>
          </el-form-item>
          <el-form-item label="description">
              <el-input type="textarea" v-model="form.a_web_description"></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>

      </div>

    </el-tab-pane>
    <el-tab-pane label="图片上传">
      <div v-if="isShow">
        <el-upload :action="createUrl" list-type="picture-card" :on-preview="handlePictureCardPreview" :file-list="fileList" :multiple="true" :auto-upload="true" :on-success="uploadSuccess" :on-remove="handlePictureRemove">
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">只能上传gif/jpg/png文件，且不超过1000kb</div>
        </el-upload>


        <el-dialog v-model="dialogVisible" size="tiny">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
        <div class="block" style="margin-top:30px;">
          <el-row>
            <el-col :span="5" v-for="(item, index) in imgs" :offset="index > 0 ? 1 : 0">
              <el-card :body-style="{ padding: '0px' }">
                <img :src="webUrl + item.f_path" class="image" @click="handlePictureCardPreview">
                <div style="padding: 14px;">
                  <span>{{ item.f_remark }}</span>
                  <div class="bottom clearfix">
                    <el-button type="text" class=" button el-icon-picture" v-show="form.h_img == item.f_path"></el-button>
                    <el-button type="text" class="button" @click="setImg(item.f_id)" v-show="form.h_img != item.f_path">设为主图</el-button>
                    <el-button type="text" class="button el-icon-delete"></el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="block" v-if="!isShow">
        <div slot="tip" class="el-upload__tip">资料保存后才能上传图片</div>
      </div>
    </el-tab-pane>
  </el-tabs>
</div>


</template>

<script>
import Objres from '@/components/common/ObjResult';
let token = localStorage.getItem('admin-token');
import MyEditor from '@/ex/MyEditor';

export default {
    data () {
        return {
            form: {
                // h_id: 0,
                a_title: '',
                a_summary: '',
                a_content: '',
                a_category: 0,
                a_img: '',
                a_click: 0,
                a_web_title: '',
                a_web_keyword: '',
                a_web_description: '',
                a_is_open: 0
            },
            editorOption: {
                modules: {
                    toolbar: '#toolbar',
                    // toolbar: [
                    //     ['bold', 'italic', 'underline', 'strike'],
                    //     ['blockquote', 'code-block'],
                    //     [{'header': 1}, {'header': 2}],
                    //     [{'list': 'ordered'}, {'list': 'bullet'}],
                    //     [{'script': 'sub'}, {'script': 'super'}],
                    //     [{'indent': '-1'}, {'indent': '+1'}],
                    //     [{'direction': 'rtl'}],
                    //     [{'size': ['small', false, 'large', 'huge']}],
                    //     [{'header': [1, 2, 3, 4, 5, 6, false]}],
                    //     [{'color': []}, {'background': []}],
                    //     [{'font': []}],
                    //     [{'align': []}],
                    //     ['clean'],
                    //     ['link']
                    //     // ['link', 'image', 'video']
                    // ],
                    // imageImport: true,
                    imageResize: {
                        displaySize: true
                    }
                }
            },
            imgs: {},
            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,
            uploadUrl: this.createUrl,
            webUrl: this.WEB_CONFIG.weburl,
            selectIndex: 0,
            categorys: [],
            categorySelect: []
        };
    },
    methods: {
        onSubmit () {
            let self = this;
            console.log('submit!');
            this.$http.post(
                self.webUrl + '/admin/article/save?token=' + token,
                self.form,
                {'emulateJSON': true}
            ).then((response) => {
                let res = response.body;
                console.log(res);
                if (res.status === Objres.ObjResult.RESULT_OK) {
                    this.$message({message: '保存成功!', type: 'success'});
                    self.$router.push('/article/' + res.data.a_id);
                } else {
                    this.$message({message: '保存失败!', type: 'error'});
                }
            });
        },
        getData (id) {
            let self = this;
            // let token = localStorage.getItem('admin-token');
            // console.log(token);
            if (token) {
                this.$http.post(
                    self.webUrl + '/admin/article/show?token=' + token + '&id=' + id,
                    self.postData,
                    {'emulateJSON': true}
                ).then((response) => {
                    let res = response.body;
                    if (res.status === Objres.ObjResult.RESULT_OK) {
                        self.form = res.data;
                        self.categoryToPath(self.form.a_category);
                    }
                });
            } else {
                this.$message({message: '请登陆', type: 'error'});
                self.$router.push('/login');
            }
        },
        getImg (id) {
            let self = this;
            if (token) {
                this.$http.get(
                    self.webUrl + '/admin/file/upload?token=' + token + '&id=' + id + '&category=Article'
                ).then((response) => {
                    let res = response.body;
                    if (res.status === Objres.ObjResult.RESULT_OK) {
                        if (res.data.length > 0) {
                            self.imgs = res.data;
                        }
                    }
                });
            } else {
                this.$message({message: '请登陆', type: 'error'});
                self.$router.push('/login');
            }
        },
        handlePictureRemove (file, fileList) {
            console.log(file, fileList);
        },
        handlePictureCardPreview (file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },
        imgsFormat (data) {
            let self = this;
            if (data.length > 0) {
                self.fileList = [];
                for (var i = 0; i < data.length; i++) {
                    self.fileList.push(
                        {
                            name: '',
                            url: self.webUrl + data[i].f_path,
                            status: 'finished'
                        }
                    );
                }
            }
        },
        uploadSuccess (res, file, fileList) {
            if (res && res.status === Objres.ObjResult.RESULT_OK) {
                this.getImg(this.$route.params.id);
            }
            console.log('uploadSuccess==res======', res);
        },
        setImg (id) {
            let self = this;
            console.log(id);
            if (token) {
                this.$http.get(
                    self.webUrl + '/admin/file/setmainimg?token=' + token + '&id=' + id
                ).then((response) => {
                    let res = response.body;
                    // console.log(res);
                    if (res.status === Objres.ObjResult.RESULT_OK) {
                        this.getData(this.$route.params.id);
                        this.$message({message: '设置主图成功!', type: 'success'});
                    }
                });
            } else {
                this.$message({message: '请登陆', type: 'error'});
                self.$router.push('/login');
            }
        },
        getCategorys () {
            let self = this;
            if (token) {
                this.$http.get(
                    self.webUrl + '/admin/category/cascader?token=' + token
                ).then((response) => {
                    let res = response.body;
                    if (res.status === Objres.ObjResult.RESULT_OK) {
                        self.categorys = res.data;
                        console.log('self.categorys', self.categorys);
                    }
                });
            } else {
                this.$message({message: '请登陆', type: 'error'});
                self.$router.push('/login');
            }
        },
        categoryChange () {
            this.form.a_category = this.categorySelect[this.categorySelect.length - 1];
            // console.log('e===0', this.categorySelect);
        },
        categoryToPath (cid) {
            let self = this;
            console.log('cid===', cid);
            if (self.categorys && cid) {
                self.pathFind(self.categorys, 'value', cid);
            }
            return self.categorySelect;
        },
        pathFind (arr, key, val) {
            let self = this;
            for (var i = 0; i < arr.length; i++) {
                if (arr[i][key] === val) {
                    self.categorySelect.splice(-1, 0, arr[i][key]);
                    return true;
                }
                if (arr[i]['children']) {
                    if (self.pathFind(arr[i]['children'], key, val)) {
                        self.categorySelect.splice(-1, 0, arr[i][key]);
                        return true;
                    };
                }
            }
        }
    },
    created () {
        this.getCategorys();
        if (this.$route.params.id) {
            console.log(this.$route.params.id);
            this.getData(this.$route.params.id);
            this.getImg(this.$route.params.id);
        }
    },
    computed: {
        isShow () {
            return 'a_id' in this.form;
        },
        createUrl () {
            if (this.isShow) {
                return this.webUrl + '/admin/file/save?id=' + this.form.a_id + '&token=' + token + '&category=Article';
            } else {
                return '';
            }
        }
    },
    components: {
        MyEditor
    }
};
</script>

<style lang="css">
.image{
    width: 100%;
}
</style>
